package hoddler

import (
	"github.com/gin-gonic/gin"
	"zy10/pkg/jwt"
	"zy10/reportily"
	"zy10/request"
	"zy10/response"
)

const JWT_TOKEN_USER = "2210A"

func Login(c *gin.Context) {
	var req request.LoginUser
	err := c.ShouldBind(&req)
	if err != nil {
		response.ResponseError(c, "错误", err.Error())
		return
	}
	user, err := reportily.LoginUser(req.Name)
	if user.Id == 0 {
		user, err = reportily.Register(req.Name, req.Password)
		if user.Id == 0 {
			response.ResponseError(c, "注册失败", err)
			return
		}
	}
	if user.Password != req.Password {
		response.ResponseError(c, "密码错误", err)
		return
	}
	claims := jwt.CustomClaims{
		ID: user.Id,
	}
	token, err := jwt.NewJWT(JWT_TOKEN_USER).CreateToken(claims)
	if err != nil {
		response.ResponseError(c, "token生成失败", err)
		return
	}
	response.ResponseSuccess(c, "登陆成功", token)
}

func List(c *gin.Context) {
	list, err := reportily.List()
	if err != nil {
		response.ResponseError(c, "查询失败", err)
		return
	}
	response.ResponseSuccess(c, "查询成功", list)

}
